<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/3/28
 * Time: 上午8:56
 * 卡券投放操作
 */

namespace app\common\controller;


use app\common\model\CardClickReplyPut;
use app\common\model\CardClickReplyPutlog;
use app\common\model\CardCzgive;
use app\common\model\CardFans;
use app\common\model\CardFansNotice;
use app\common\model\CardFansNoticeLog;
use app\common\model\CardFollowcard;
use app\common\model\CardFollowcardlog;
use app\common\model\CardGeneral;
use app\common\model\CardGive;
use app\common\model\CardGivecardLog;
use app\common\model\CardGivePutCard;
use app\common\model\CardGivePutCardUser;
use app\common\model\CardMember;
use app\common\model\CardPaycard;
use app\common\model\CardPaycardlog;
use app\common\model\CardShareLog;
use app\common\model\CardUserGet;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\Paylog;
use app\common\model\PaymentCardPut;
use app\common\model\PaymentCardPutLog;
use app\common\model\WxOpen;
use app\merchant\controller\Wxtemlpmesg;
use think\Controller;
use Wnkj\WnCardObj;
use Wnkj\WnObj;

class CardPut extends Wxoption
{

    //检查规则
    public function checkgive($arr)
    {

        if ($arr['giveid'] == '' || $arr['giveid'] == "0" || $arr['giveid'] == null || empty($arr['giveid'])) {
            $arrc['add_balance'] = $arr['add_balance'];
            $arrc['pay_balance'] = $arr['add_balance'];
        } else {
            $CardZsgive = new CardCzgive();
            $zsgive = $CardZsgive->where('id', $arr['giveid'])->field('cz_money,zs_money')->find();
            $arrc['add_balance'] = $zsgive['cz_money'] + $zsgive['zs_money'];
            $arrc['pay_balance'] = $zsgive['cz_money'];
        }
        return $arrc;
    }


    //充值赠送
    /*
     *  giveid  openid  nickname  code  mid  give_rec_id
     * */
    public function regSgive($param)
    {
        $CardCzgive = new CardCzgive();
        $giveid = $param['giveid'];
        $zs_card = $CardCzgive->where('id', $giveid)->value('zs_card');
        if ($zs_card > 0) {
            $arr['zs_card_id_all'] = $CardCzgive->where('id', $giveid)->value('zs_card_id_all');
            $arr['code'] = $param['code'];
            $arr['openid'] = $param['openid'];
            $arr['mid'] = $param['mid'];
            $arr['card_id'] = $param['card_id'];
            $arr['give_rec_id'] = $param['give_rec_id'];
            $arr['top_mid'] = $param['top_mid'];
            $res = $this->get_zs_cardslog($arr);
            if ($res) {
                $SendMsg = new TemplateMsg();
                $arrs['mid'] = $param['mid'];
                $arrs['openid'] = $param['openid'];
                $arrs['card_id'] = $param['card_id'];
                $arrs['name'] = $param['nickname'];
                $arrs['title'] = '充值送券';
                $arrs['rec_id'] = $param['give_rec_id'];
                $arrs['type'] = 'recharge';
                $resu = $SendMsg->send_tpl('put_gift', $arrs);
            } else {
                $resu = '';
            }
            $resut['card'] = $resu;
        } else {
            $resut['card'] = '无券赠送';
        }
//        //赠送积分
//        $zs_bonus = $CardCzgive->where('id', $giveid)->value('bonus');
//        if (!empty($zs_bonus)) {
//            $zs_params['giveid'] = $param['giveid'];
//            $zs_params['code'] = $param['code'];
//            $zs_params['card_id'] = $param['card_id'];
//            $zs_params['get_card_id'] = $param['get_card_id'];
//            $ComBonus = new Bonus();
        $resut['bonus'] = '';
//        } else {
//            $resut['bonus'] = '无积分赠送';
//        }
        return $resut;
    }


    //生成赠卡记录
    /*
     * zs_card_id_all / card_id  /code /  give_rec_id  / mid / top_mid
     * */
    public function get_zs_cardslog($arr)
    {
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $arr['zs_card_id_all'];
        if ($zs_card_id) {
            $zs_card_id = json_decode($arr['zs_card_id_all'], true);
            $datass['cardlist'] = $zs_card_id;
            $WnObj = new WnObj($datass);
            $arrs = $WnObj->isgetputsume_rec();
            $data = [];
            if (!empty($arrs)) {
                $CardUserGet = new CardUserGet();
                $user = $CardUserGet->where(array('openid' => $arr['openid'], 'card_id' => $arr['card_id']))->field('id,c_id')->find();
                foreach ($arrs as $k => $v) {
                    $data[$k]['card_id'] = $arr['card_id'];
                    $data[$k]['openid'] = $arr['openid'];
                    $data[$k]['us_c_id'] = $user['id'];
                    $data[$k]['c_id'] = $user['c_id'];
                    $data[$k]['code'] = $arr['code'];
                    $data[$k]['zs_card_id'] = $v['card_id'];
                    $data[$k]['give_rec_id'] = $arr['give_rec_id'];
                    $data[$k]['mid'] = $arr['mid'];
                    $data[$k]['top_mid'] = $arr['top_mid'];
                    $data[$k]['put_sume'] = $v['zs_no'];
                    $data[$k]['put_type'] = 'recharge_cards';
                    $data[$k]['create_time'] = time();
                }
            }
            $res = $CardGivecardLog->saveAll($data);
        } else {
            $res = '';
        }
        return $res;
    }

    //充值赠送
    public function czgive($param)
    {
        $CardCzgive = new CardCzgive();
        $giveid = $param['giveid'];
        $wxmsg = new Wxtemlpmesg();
        //赠送卡券
        $zs_card = $CardCzgive->where('id', $giveid)->value('zs_card');
        if ($zs_card > 0) {
            //多张
            if ($zs_card > 1) {
                $data_tpl_zs['openid'] = $param['openid'];
                $data_tpl_zs['card_id'] = $CardCzgive->where('id', $giveid)->value('card_id');
                $data_tpl_zs['name'] = $param['nickname'];
                $data_tpl_zs['give'] = $giveid;
                $data_tpl_zs['title'] = '充值赠送';
                $resut = $wxmsg->putCardlist($data_tpl_zs);
                $resut['card'] = $resut;
            } else {
                //单张
                $data_tpl_zs['openid'] = $param['openid'];
                $data_tpl_zs['card_id'] = $CardCzgive->where('id', $giveid)->value('zs_card_id');
                $data_tpl_zs['name'] = $param['nickname'];
                $data_tpl_zs['title'] = '充值赠送';
                $resut = $wxmsg->putCard($data_tpl_zs);
                $resut['card'] = $resut;
            }
        } else {
            $resut['card'] = '无券赠送';
        }
        //赠送积分
//        $zs_bonus = $CardCzgive->where('id', $giveid)->value('bonus');
//        if (!empty($zs_bonus)) {
//            $zs_params['giveid'] = $param['giveid'];
//            $zs_params['code'] = $param['code'];
//            $zs_params['card_id'] = $param['card_id'];
//            $zs_params['get_card_id'] = $param['get_card_id'];
//            $ComBonus = new Bonus();
//            $resut['bonus'] = $ComBonus->cs_bonus_rec($zs_params);
//        } else {
        $resut['bonus'] = '';
//        }
        return $resut;
    }

    //开卡送券
    public function firecards($arr)
    {

        $CardGive = new CardGive();
        $CardUserGet = new CardUserGet();
        $sql['card_id'] =  $arr['card_id'];
        $sql['statu'] =  ['neq',2];
        $giveinfo = $CardGive->where($sql)->find();
        $user = $CardUserGet->where(['card_id' => $arr['card_id'], 'code' => $arr['code']])->field('fire')->find();
        if ($user['fire'] == "1" || $user['fire'] == 1) {
            if ($giveinfo) {
                if ($giveinfo['end_time'] > time()) {
                    if ($giveinfo['card_no'] > 0) {
                        $arr['card_id_list'] = $giveinfo['card_id_list'];
                        $arr['give_id'] = $giveinfo['id'];
                        $CardGivePutCard = new CardGivePutCard();
                        $data['top_mid'] = $arr['top_mid'];
                        $data['mid'] = $arr['mid'];
                        $data['code'] = $arr['code'];
                        $data['card_id'] = $arr['card_id'];
                        $data['openid'] = $arr['openid'];
                        $data['give_type'] = 'fire_card';
                        $data['give_id'] = $giveinfo['id'];
                        $data['create_time'] = time();
                        $CardGivePutCard->allowField(true)->save($data);
                        $arr['give_rec_id'] = $CardGivePutCard->id;
                        $res = $this->get_fire_cardslog($arr);
                        if ($res) {
                            $SendMsg = new TemplateMsg();
                            $arrs['mid'] = $arr['mid'];
                            $arrs['openid'] = $arr['openid'];
                            $arrs['card_id'] = $arr['card_id'];
                            $arrs['name'] = $arr['nickname'];
                            $arrs['title'] = '开卡有礼';
                            $arrs['give_id'] = $giveinfo['id'];
                            $arrs['type'] = 'fire';
                            $arrs['url'] = '/mobile.php?s=/cardget/getfirecards/card_id/' . $arr['card_id'] . '/rec_id/' . $arr['give_rec_id'];
                            $resu = $SendMsg->send_tpl('put_gift', $arrs);
                        } else {
                            $resu = '';
                        }
                        $resut['card'] = $resu;
                        $datac['giveinfo'] = json_encode($resut, JSON_UNESCAPED_UNICODE);
                        $CardGivePutCard->allowField(true)->save($datac);
                    } else {
                        $resut['card'] = '无券赠送1';
                    }
                } else {
                    $resut['card'] = '已结束';
                }
            } else {
                $resut['card'] = '无券赠送2';
            }
        } else {
            $resut['card'] = '未激活';
        }
        return $resut;
    }

    //开卡送券记录
    public function get_fire_cardslog($arr)
    {
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $arr['card_id_list'];
        if ($zs_card_id) {
            $zs_card_id = json_decode($arr['card_id_list'], true);
            $data = [];
            foreach ($zs_card_id as $k => $v) {
                if (filteroffcard($v['zs_card_id']) == true) {
                    $data[$k]['card_id'] = $arr['card_id'];
                    $data[$k]['openid'] = $arr['openid'];
                    $data[$k]['code'] = $arr['code'];
                    $data[$k]['put_type'] = 'fire_card';
                    $data[$k]['zs_card_id'] = $v['zs_card_id'];
                    $data[$k]['give_rec_id'] = $arr['give_rec_id'];
                    $data[$k]['mid'] = $arr['mid'];
                    $data[$k]['top_mid'] = $arr['top_mid'];
                    $data[$k]['put_sume'] = $v['zs_no'];
                    $data[$k]['create_time'] = time();
                }
            }
            $res = $CardGivecardLog->allowField(true)->saveAll($data);
        } else {
            $res = '';
        }
        return $res;
    }

    //付费购券
    /*
     *  giveid  openid  nickname  code  mid  give_rec_id  top_mid
     * */
    public function payregsgive($param)
    {


        $CardPaycard = new CardPaycard();
        $giveid = $param['giveid'];
        $zs_card = $CardPaycard->where('id', $giveid)->value('cardlist');
        $card_no = count(json_decode($zs_card, true));

        if ($card_no > 0) {
            $arr['zs_card_id_all'] = $zs_card;
            $arr['openid'] = $param['openid'];
            $arr['code'] = $param['code'];
            $arr['mid'] = $param['mid'];
            $arr['card_id'] = $param['card_id'];
            $arr['give_rec_id'] = $param['give_rec_id'];
            $arr['top_mid'] = $param['top_mid'];

            $res = $this->pay_zs_cardslog($arr);
            if ($res) {
                $SendMsg = new TemplateMsg();
                $arrs['mid'] = $arr['mid'];
                $arrs['openid'] = $arr['openid'];
                $arrs['card_id'] = $arr['card_id'];
                $arrs['name'] = $param['nickname'];
                $arrs['title'] = '卡券购买';
                $arrs['give_id'] = $giveid;
                $arrs['type'] = 'paycard';
                $arrs['url'] = '/mobile.php?s=/cardget/getpaycards/card_id/' . $arr['card_id'] . '/rec_id/' . $arr['give_rec_id'];
                $resu = $SendMsg->send_tpl('put_gift', $arrs);
            } else {
                $resu = '';
            }
            $resut['card'] = $resu;
            $datac['giveinfo'] = json_encode($resut, JSON_UNESCAPED_UNICODE);
            $datac['paystatu'] = 1;
            $datac['paytime'] = time();
            $CardPaycardlog = new CardPaycardlog();
            $CardPaycardlog->allowField(true)->save($datac, ['id' => $param['give_rec_id']]);
            $CardPaycard->where(['id' => $giveid])->setInc('get_num');
        } else {
            $resut['card'] = '无券赠送';
        }

        return $resut;
    }

    //付费购券(非领卡会员)
    /*
     *   openid  mid  top_mid giveid give_rec_id
     * */
    public function payregsgivenotuser($param)
    {
        $CardPaycard = new CardPaycard();
        $giveid = $param['giveid'];
        $zs_card = $CardPaycard->where('id', $giveid)->value('cardlist');
        $card_no = count(json_decode($zs_card, true));
        if ($card_no > 0) {
            $arr['zs_card_id_all'] = $zs_card;
            $arr['openid'] = $param['openid'];
            $arr['code'] = '';
            $arr['mid'] = $param['mid'];
            $arr['card_id'] = '';
            $arr['give_rec_id'] = $param['give_rec_id'];
            $arr['top_mid'] = $this->get_topmid_mid($param['mid']);
            $res = $this->pay_zs_cardslog($arr);
            if ($res) {
                $SendMsg = new TemplateMsg();
                $arrs['mid'] = $arr['mid'];
                $arrs['openid'] = $arr['openid'];
                $arrs['card_id'] = '';
                $arrs['name'] = '';
                $arrs['title'] = '卡券购买';
                $arrs['give_id'] = $giveid;
                $arrs['type'] = 'paycard';
                $arrs['url'] = '/mobile.php?s=/cardget/getpaycards/mid/' . $arr['mid'] . '/rec_id/' . $arr['give_rec_id'];
                $resu = $SendMsg->send_tpl('put_gift', $arrs);
            } else {
                $resu = '';
            }
            $resut['card'] = $resu;
            $datac['giveinfo'] = json_encode($resut, JSON_UNESCAPED_UNICODE);
            $datac['paystatu'] = 1;
            $datac['paytime'] = time();
            $CardPaycardlog = new CardPaycardlog();
            $CardPaycardlog->allowField(true)->save($datac, ['id' => $param['give_rec_id']]);
            $CardPaycard->where(['id' => $giveid])->setInc('get_num');
        } else {
            $resut['card'] = '无券赠送';
        }
        return $resut;
    }

    //生成赠卡记录
    /*
     * zs_card_id_all / card_id  /code /  give_rec_id  / mid / top_mid
     * */
    public function pay_zs_cardslog($arr)
    {
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $arr['zs_card_id_all'];
        if ($zs_card_id) {
            $zs_card_id = json_decode($arr['zs_card_id_all'], true);
            $data = [];
            foreach ($zs_card_id as $k => $v) {
                $is_pay = filterispay($v['zs_card_id']);
                $is_off = filteroffcard($v['zs_card_id']);
                if ($is_pay == true && $is_off == true) {
                    $data[$k]['card_id'] = $arr['card_id'];
                    $data[$k]['openid'] = $arr['openid'];
                    $data[$k]['code'] = $arr['code'];
                    $data[$k]['zs_card_id'] = $v['zs_card_id'];
                    $data[$k]['give_rec_id'] = $arr['give_rec_id'];
                    $data[$k]['mid'] = $arr['mid'];
                    $data[$k]['top_mid'] = $arr['top_mid'];
                    $data[$k]['put_sume'] = $v['zs_no'];
                    $data[$k]['put_type'] = 'paycard';
                    $data[$k]['create_time'] = time();
                }
            }
            $res = $CardGivecardLog->saveAll($data);
        } else {
            $res = '';
        }
        return $res;
    }


    //关注送券
    /*
     * openid  gh_id
     */
    public function followcardput($param)
    {
        try {
            $CardFollowcard = new CardFollowcard();
            $CardFollowcardlog = new CardFollowcardlog();
            $openid = $param['openid'];
            $appid = $this->getappid_ghid($param['gh_id']);
            $top_mid = $this->gettopmid_wxopenid($appid['id']);
            $map['top_mid'] = $top_mid;
            $map['status'] = 1;
            $map['starttime'] = array('elt', time());
            $map['endtime'] = array('egt', time());
            $putcard = $CardFollowcard->where($map)->find();
            if ($putcard) {
                if ($putcard['type'] == 3) {
                    $arrs = [
                        [
                            'Title' => $putcard['title'],
                            'Description' => $putcard['description'],
                            'PicUrl' => $putcard['img'],
                            'Url' => $putcard['url']
                        ]
                    ];
                    return $arrs;
                }
                $fans = $CardFollowcardlog->where(['gh_id' => $param['gh_id'], 'openid' => $param['openid']])->find();
                if ($fans) {
                    exit();
                }
                if ($putcard) {
                    $CardUserGet = new CardUserGet();
                    $maps['openid'] = $openid;
                    $maps['top_mid'] = $top_mid;
                    $maps['have'] = 1;
                    $maps['fire'] = 1;
                    $maps['card_type'] = 'MEMBER_CARD';
                    $user = $CardUserGet->where($maps)->field('openid,code,card_id')->find();
                    //增加关注记录
                    $data['openid'] = $openid;
                    $data['top_mid'] = $top_mid;
                    $data['gh_id'] = $param['gh_id'];
                    $data['appid'] = $appid['authorizer_appid'];
                    $data['fid'] = $putcard['id'];
                    $data['followstatu'] = 1;
                    $data['followtime'] = time();
                    $data['zs_card_id'] = $putcard['cardlist'];
                    $data['bonus'] = $putcard['bonus'];
                    $CardFollowcardlog->allowField(true)->save($data);
                    $give_rec_id = $CardFollowcardlog->id;
                    //是否积分
                    if ($putcard['is_bonus'] == "Y" && $user) {
                        $option['card_id'] = $user['card_id'];
                        $option['code'] = $user['code'];
                        $option['orderid'] = '';
                        $option['num'] = $data['bonus'];
                        $option['bd_cate'] = 'bonus';
                        $option['type'] = 1;//变动 1增加 2减少
                        $option['cate'] = 11;  //变动类型
                        $option['pay_cate'] = 4; //支付方式
                        $option['source'] = 'web';  //来源
                        $option['remark'] = $putcard['title']; //备注
                        $option['action_user'] = 'web';//操作人
                        $Fztest = new WnCardObj($option);
                        $arrs = $Fztest->init();
                        $dataput['get_num'] = $putcard['get_num'] + 1;
                        $CardFollowcard->save($dataput,['id' => $putcard['id']]);
                    }
                    if ($putcard['num'] > $putcard['get_num'] && $putcard['is_cards'] == "Y") {
                        $card_no = count(json_decode($putcard['cardlist'], true));
                        if ($card_no > 0) {
                            //END
                            //生成赠卡信息
                            $arr['zs_card_id_all'] = $putcard['cardlist'];
                            $arr['openid'] = $openid;
                            $arr['code'] = 'public';
                            $arr['mid'] = $this->getmid_topmid($top_mid);
                            $arr['card_id'] = '';
                            $arr['give_rec_id'] = $give_rec_id;
                            $arr['top_mid'] = $top_mid;
                            $res = $this->follow_zs_cardslog($arr);
                            //END
                            if ($res) {
                                //发送图文消息
                                $Platurl = new Platurl();
                                $agent_url = $Platurl->getagenturl('top_mid', $top_mid);
                                $arrs = [
                                    [
                                        'Title' => $putcard['title'],
                                        'Description' => $putcard['description'],
                                        'PicUrl' => $putcard['img'],
                                        'Url' => $agent_url . '/mobile.php?s=/cardget/getfollowcards/mid/' . $arr['mid'] . '/rec_id/' . $arr['give_rec_id']
                                    ]
                                ];
                                //END
                            } else {
                                $arrs = 0;
                            }
                            //更新
                            $datac['giveinfo'] = json_encode($arrs, JSON_UNESCAPED_UNICODE);
                            $CardFollowcardlog->allowField(true)->save($datac, ['id' => $give_rec_id]);
                            $dataput['get_num'] = $putcard['get_num'] + 1;
                            $CardFollowcard->save($dataput,['id' => $putcard['id']]);
                            //END
                        } else {
                            //赠送数小于0
                            $arrs = 1;
                        }
                    } else {
                        //已发送完
                        $arrs = 2;
                    }
                } else {
                    //无赠送规则
                    $arrs = 3;
                }
            }else{
                $arrs = 3;
            }
            return $arrs;
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
   
        }
    }


    //生成赠卡记录
    /*
     * zs_card_id_all / card_id  /code /  give_rec_id  / mid / top_mid
     * */
    public function follow_zs_cardslog($arr)
    {
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $arr['zs_card_id_all'];
        if ($zs_card_id) {
            $zs_card_id = json_decode($arr['zs_card_id_all'], true);

            $data = [];
            foreach ($zs_card_id as $k => $v) {
                if (filterispay($v['zs_card_id']) == false && filteroffcard($v['zs_card_id']) == true) {
                    $data[$k]['card_id'] = $arr['card_id'];
                    $data[$k]['openid'] = $arr['openid'];
                    $data[$k]['code'] = $arr['code'];
                    $data[$k]['zs_card_id'] = $v['zs_card_id'];
                    $data[$k]['give_rec_id'] = $arr['give_rec_id'];
                    $data[$k]['mid'] = $arr['mid'];
                    $data[$k]['top_mid'] = $arr['top_mid'];
                    $data[$k]['put_sume'] = $v['zs_no'];
                    $data[$k]['put_type'] = 'follow_card';
                    $data[$k]['create_time'] = time();
                }

            }

            $res = $CardGivecardLog->saveAll($data);
        } else {
            $res = '';
        }
        return $res;

    }

    //支付后送券
    public function paymentputcard($param,$payment){
        $Paylog = new Paylog();
        $payinfo = $Paylog->where(['orderid'=>$param['orderid']])->find();
        //是否发送过
        if ($payinfo['pay_is_put'] == 0 || $payinfo['pay_is_put'] == '0'){
            $Merchant = new Merchant();
            $top_mid = $Merchant->where(['id'=>$payinfo['mid']])->value('top_mid');
            $PaymentCardPut = new PaymentCardPut();
            $map['top_mid'] = $top_mid;
            $map['statu'] = 1;

            $CardMember = new CardMember();
            $CardUserGet = new CardUserGet();
            $cardus = $CardMember->where(['top_mid'=>$top_mid])->field('card_id')->find();
            $user = $CardUserGet->where(['card_id'=>$cardus['card_id'],'openid'=>$payinfo['openid']])->field('nickname,code,card_id')->find();

            if ($payment['num'] > $payment['get_num']){
                $card_no = count(json_decode($payment['zs_card_id_all'],true));
                if($card_no > 0){
                    $arr['zs_card_id_all'] = $payment['zs_card_id_all'];
                    $arr['openid'] = $payinfo['openid'];
                    $arr['code'] = $user['code'];
                    $arr['mid'] = $payinfo['mid'];
                    $arr['card_id'] = $cardus['card_id'];
                    $arr['give_rec_id'] = $param['give_rec_id'];
                    $arr['top_mid'] = $top_mid;
                    $res = $this->payment_zs_cardslog($arr);
                    if ($res) {
                        $SendMsg = new TemplateMsg();
                        $arrs['first'] = '点击“详情”领取优惠券';
                        $arrs['mid'] = $arr['mid'];
                        $arrs['openid'] = $arr['openid'];
                        $arrs['card_id'] = '';
                        $arrs['name'] = $user['nickname'] == ''?'您好':$user['nickname'];
                        $arrs['title'] = $payment['zs_card_info'];
                        $arrs['give_id'] = $payment['id'];
                        $arrs['type'] = 'paymentcard';
                        $arrs['url'] = '/mobile.php?s=/cardget/getpaymentcards/mid/' . $arr['mid'] . '/rec_id/' . $arr['give_rec_id'];
                        $resu = $SendMsg->send_tpl('put_gift', $arrs);
                    } else {
                        $resu = '';
                    }
                    $resut['card'] = $resu;
                    $datac['giveinfo'] = json_encode($resut, JSON_UNESCAPED_UNICODE);
                    $datac['paystatu'] = 1;
                    $datac['paytime'] = time();
                    $PaymentCardPutLog = new PaymentCardPutLog();
                    $PaymentCardPutLog->allowField(true)->save($datac,['id'=>$param['give_rec_id']]);
                    $PaymentCardPut->where(['id'=>$payment['id']])->setInc('get_num');
                } else {
                    $resut['card'] = '无券赠送';
                }
            }else{
                $resut = 'error3';
            }

        }else{
            $resut = 'error1';
        }
        return $resut;
    }

    //生成赠卡记录[支付后
    /*
     * zs_card_id_all / card_id  /code /  give_rec_id  / mid / top_mid  / put_type
     * */
    public function payment_zs_cardslog($arr){
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $arr['zs_card_id_all'];
        if ($zs_card_id){
            $zs_card_id = json_decode($arr['zs_card_id_all'],true);

            $data = [];
            foreach ($zs_card_id as $k=>$v) {
                if (filterispay($v['zs_card_id']) == false && filteroffcard($v['zs_card_id']) == true) {
                    $data[$k]['mid'] = $arr['mid'];
                    $data[$k]['card_id'] = $arr['card_id'];
                    $data[$k]['code'] = $arr['code'];
                    $data[$k]['openid'] = $arr['openid'];
                    $data[$k]['zs_card_id'] = $v['zs_card_id'];
                    $data[$k]['give_rec_id'] = $arr['give_rec_id'];
                    $data[$k]['mid'] = $arr['mid'];
                    $data[$k]['top_mid'] = $arr['top_mid'];
                    $data[$k]['put_sume'] = $v['zs_no'];
                    $data[$k]['put_type'] = 'payment_card';
                    $data[$k]['create_time'] = time();
                }
            }

            $res = $CardGivecardLog->saveAll($data);
        }else{
            $res = '';
        }
        return $res;
    }


    //分享送券
    //arr:user  code  card_id  mid  openid  nickname    share:shareinfo  zs_card_info  zs_card_id_all
    public function putsharecards($param,$share)
    {
        try {
            $CardShareLog = new CardShareLog();

            $data['zs_card_info'] = $share['zs_card_info'];
            $data['share_info'] = json_encode($share,JSON_UNESCAPED_UNICODE);
            $map['get_code'] = $param['get_code'];
            $map['card_id'] = $param['card_id'];
            $give_rec_id = $CardShareLog->where($map)->value('id');
            if ($give_rec_id) {
                $CardShareLog->allowField(true)->save($data, $map);


                $param['give_rec_id'] = $give_rec_id;
                $res = $this->get_share_cardslog($param, $share);
                if ($res && $share['is_notice'] == 'Y') {
                    $CardUserGet = new CardUserGet();
                    $Momchant = new Momerchant();
                    $maps['code'] = $param['get_code'];
                    $maps['card_id'] = $param['card_id'];
                    $getuser = $CardUserGet->where($maps)->field('nickname,top_mid')->find();
                    $Momach = $Momchant->where('id',$getuser['top_mid'])->field('merchant_name')->find();
                    //END
                    $SendMsg = new TemplateMsg();
                    $arrs['first'] = '您好,您的好友@'.$getuser['nickname'].'通过邀请成为了'.$Momach['merchant_name'].'会员，邀请奖励已放入您的会员卡,请查收~';
                    $arrs['mid'] = $param['mid'];
                    $arrs['openid'] = $param['openid'];
                    $arrs['name'] = $param['nickname'];
                    $arrs['title'] = $share['zs_card_info'];
                    $arrs['card_id'] = $param['card_id'];
                    $arrs['rec_id'] = $give_rec_id;
                    $arrs['type'] = 'sharecard';
                    $arrs['url'] = '/mobile.php?s=/cardget/getsharecards/card_id/' . $param['card_id'] . '/rec_id/' . $give_rec_id;
                    $resu = $SendMsg->send_tpl('put_gift', $arrs);
                } else {
                    $resu = '';
                }
            }else{
                $resu = '';
            }
            return $resu;
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            return '';
        }
    }

    //分享送券记录
    public function get_share_cardslog($param,$share){
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $share['zs_card_id_all'];
        if ($zs_card_id){
            $zs_card_id = json_decode($share['zs_card_id_all'],true);
            $data = [];
            foreach ($zs_card_id as $k=>$v) {
                $data[$k]['card_id'] = $param['card_id'];
                $data[$k]['code'] = $param['code'];
                $data[$k]['openid'] = $param['openid'];
                $data[$k]['zs_card_id'] = $v['zs_card_id'];
                $data[$k]['give_rec_id'] = $param['give_rec_id'];
                $data[$k]['mid'] = $param['mid'];
                $data[$k]['top_mid'] = $param['top_mid'];
                $data[$k]['put_sume'] = $v['zs_no'];
                $data[$k]['put_type'] = 'share_card';
                $data[$k]['create_time'] = time();
            }

            $res = $CardGivecardLog->saveAll($data);
        }else{
            $res = '';
        }
        return $res;
    }

    //等级送券
    //rec_id  remark  mid  openid  nickname  zs_card_info   card_id  code
    public function putrankcards($param)
    {
        $param['give_rec_id'] = $param['rec_id'];
        $res = $this->get_rank_cardslog($param);
        if ($res) {
            //END
            $SendMsg = new TemplateMsg();
            $arrs['first'] = $param['remark'].'点击“详情”领取优惠券';
            $arrs['mid'] = $param['mid'];
            $arrs['openid'] = $param['openid'];
            $arrs['name'] = $param['nickname'];
            $arrs['title'] = $param['zs_card_info'];
            $arrs['card_id'] = $param['card_id'];
            $arrs['rec_id'] = $param['rec_id'];
            $arrs['type'] = 'rankcard';
            $arrs['url'] = '/mobile.php?s=/cardget/getrankcards/card_id/' . $param['card_id'] . '/rec_id/' . $param['rec_id'];
            $resu = $SendMsg->send_tpl('put_gift', $arrs);
        } else {
            $resu = '';
        }
        $resu = 0;
        return $resu;
    }

    //等级送券记录
    public function get_rank_cardslog($param){
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $param['zs_card_id_all'];
        if ($zs_card_id){
            $zs_card_id = json_decode($param['zs_card_id_all'],true);
            $data = [];
            foreach ($zs_card_id as $k=>$v) {
                $data[$k]['card_id'] = $param['card_id'];
                $data[$k]['code'] = $param['code'];
                $data[$k]['openid'] = $param['openid'];
                $data[$k]['zs_card_id'] = $v['zs_card_id'];
                $data[$k]['give_rec_id'] = $param['give_rec_id'];
                $data[$k]['mid'] = $param['mid'];
                $data[$k]['top_mid'] = $param['top_mid'];
                $data[$k]['put_sume'] = $v['zs_no'];
                $data[$k]['put_type'] = 'rank_card';
                $data[$k]['create_time'] = time();
            }

            $res = $CardGivecardLog->saveAll($data);
        }else{
            $res = '';
        }
        return $res;
    }

    //点击菜单送券
    public function clickmenuputcard($param)
    {
        $CardClickReplyPut = new CardClickReplyPut();
        $CardClickReplyPutlog = new CardClickReplyPutlog();
        $openid = $param['openid'];
        $appid = $this->getappid_ghid($param['gh_id']);
        $top_mid = $this->gettopmid_wxopenid($appid['id']);
        $map['top_mid'] = $top_mid;
        $map['status'] = 1;
        $map['give_type'] = 1;
        $map['click_key'] = $param['click_key'];
        $putcard = $CardClickReplyPut->where($map)->find();
        $isput = $CardClickReplyPutlog->where(['gh_id' => $param['gh_id'], 'openid' => $param['openid'],'click_id'=>$putcard['id']])->count();
        if ($isput == $putcard['limit_num']) {
            exit();
        }

        if ($putcard) {
            $CardUserGet = new CardUserGet();
            $maps['openid'] = $openid;
            $maps['top_mid'] = $top_mid;
            $maps['have'] = 1;
            $maps['fire'] = 1;
            $maps['card_type'] = 'MEMBER_CARD';
            $user = $CardUserGet->where($maps)->field('openid,code,card_id')->find();
            //增加关注记录
            $data['openid'] = $openid;
            $data['top_mid'] = $top_mid;
            $data['gh_id'] = $param['gh_id'];
            $data['appid'] = $appid['authorizer_appid'];
            $data['click_id'] = $putcard['id'];
            $data['cardlist'] = $putcard['cardlist'];
            $data['give_type'] = $putcard['give_type'];
            $data['putstatu'] = 1;
            $data['puttime'] = time();
            $data['zs_card_id'] = $putcard['cardlist'];
//            $data['bonus'] = $putcard['bonus'];
            $CardClickReplyPutlog->allowField(true)->save($data);
            $give_rec_id = $CardClickReplyPutlog->id;
            //是否积分
            if ($putcard['is_bonus'] == "Y" && $user) {
                $option['card_id'] = $user['card_id'];
                $option['code'] = $user['code'];
                $option['orderid'] = '';
                $option['num'] = $data['bonus'];
                $option['bd_cate'] = 'bonus';
                $option['type'] = 1;//变动 1增加 2减少
                $option['cate'] = 11;  //变动类型
                $option['pay_cate'] = 4; //支付方式
                $option['source'] = 'web';  //来源
                $option['remark'] = $putcard['title']; //备注
                $option['action_user'] = 'web';//操作人
                $Fztest = new WnCardObj($option);
                $arrs = $Fztest->init();
                $dataput['get_num'] = $putcard['get_num'] + 1;
                $CardClickReplyPut->save($dataput,['id' => $putcard['id']]);
            }
            if ($putcard['num'] > $putcard['get_num'] && $putcard['is_cards'] == "Y") {
                $card_no = count(json_decode($putcard['cardlist'], true));
                if ($card_no > 0) {
                    //生成赠卡信息
                    $arr['zs_card_id_all'] = $putcard['cardlist'];
                    $arr['openid'] = $openid;
                    $arr['code'] = 'public';
                    $arr['mid'] = $this->getmid_topmid($top_mid);
                    $arr['card_id'] = '';
                    $arr['give_rec_id'] = $give_rec_id;
                    $arr['top_mid'] = $top_mid;
                    $arr['put_card'] = 'click_card';
                    $res = $this->click_zs_cardslog($arr);
                    //END
                    if ($res) {
                        //发送图文消息
                        $Platurl = new Platurl();
                        $agent_url = $Platurl->getagenturl('top_mid', $top_mid);
                        $arrs = [
                            [
                                'Title' => $putcard['title'],
                                'Description' => $putcard['description'],
                                'PicUrl' => $putcard['img'],
                                'Url' => $agent_url . '/mobile.php?s=/cardget/getclickmsgcards/mid/' . $arr['mid'] . '/rec_id/' . $arr['give_rec_id']
                            ]
                        ];

                    } else {
                        $arrs = 0;
                    }
                    //更新
                    $datac['giveinfo'] = json_encode($arrs, JSON_UNESCAPED_UNICODE);
                    $CardClickReplyPutlog->allowField(true)->save($datac, ['id' => $give_rec_id]);
                    $dataput['get_num'] = $putcard['get_num'] + 1;
                    $CardClickReplyPut->save($dataput,['id' => $putcard['id']]);
                    //END
                } else {
                    //赠送数小于0
                    $arrs = 1;
                }
            } else {
                //已发送完
                $arrs = 2;
            }
        } else {
            //无赠送规则
            $arrs = 3;
        }
        return $arrs;
    }


    //回复关键词送券
    public function replymsgputcard($param){

        $CardClickReplyPut = new CardClickReplyPut();
        $CardClickReplyPutlog = new CardClickReplyPutlog();
        $openid = $param['openid'];
        $appid = $this->getappid_ghid($param['gh_id']);
        $top_mid = $this->gettopmid_wxopenid($appid['id']);
        $map['top_mid'] = $top_mid;
        $map['status'] = 1;
        $map['msg_key'] = $param['msg_key'];
        $putcard = $CardClickReplyPut->where($map)->find();

        if ($putcard){
            $isput = $CardClickReplyPutlog->where(['openid'=>$param['openid'],'click_id'=>$putcard['id']])->count();
            if ($putcard['num'] > $putcard['get_num'] && $isput < $putcard['limit_num']){
                $card_no = count(json_decode($putcard['cardlist'],true));
                if($card_no > 0){
                    //增加点击记录
                    $data['openid'] = $openid;
                    $data['top_mid'] = $top_mid;
                    $data['gh_id'] = $param['gh_id'];
                    $data['appid'] = $appid['authorizer_appid'];
                    $data['click_id'] = $putcard['id'];
                    $data['cardlist'] = $putcard['cardlist'];
                    $data['putstatu'] = 1;
                    $data['putime'] = time();
                    $data['zs_card_id'] = $putcard['cardlist'];
                    $CardClickReplyPutlog->allowField(true)->save($data);
                    $give_rec_id = $CardClickReplyPutlog->id;
                    //END
                    //生成赠卡信息
                    $arr['zs_card_id_all'] = $putcard['cardlist'];
                    $arr['openid'] = $openid;
                    $arr['code'] = 'public';
                    $arr['mid'] = $this->getmid_topmid($top_mid);
                    $arr['card_id'] = '';
                    $arr['give_rec_id'] = $give_rec_id;
                    $arr['top_mid'] = $top_mid;
                    $arr['put_card'] = 'replymsg_card';
                    $res = $this->click_zs_cardslog($arr);
                    if ($res) {
                        //发送图文消息
                        $Platurl = new Platurl();
                        $agent_url = $Platurl->getagenturl('top_mid',$top_mid);
                        $arrs = [
                            [
                                'Title' => $putcard['title'],
                                'Description' => $putcard['description'],
                                'PicUrl' => $putcard['img'],
                                'Url' => $agent_url.'/mobile.php?s=/cardget/getclickmsgcards/mid/' . $arr['mid'] . '/rec_id/' . $arr['give_rec_id']
                            ]
                        ];

                    } else {
                        $arrs = 0;
                    }
                    //更新
                    $datac['giveinfo'] = json_encode($arrs, JSON_UNESCAPED_UNICODE);
                    $CardClickReplyPutlog->allowField(true)->save($datac,['id'=>$give_rec_id]);
                    $CardClickReplyPut->where(['id'=>$putcard['id']])->setInc('get_num');
                    //END
                }else{
                    //赠送数小于0
                    $arrs = 1;
                }
            }else{
                //已发送完
                $arrs = 2;
            }
        }else{
            //无赠送规则
            $arrs = 3;
        }
        return $arrs;
    }



    //生成赠卡记录[自定义菜、关键字回复
    /*
     * zs_card_id_all / card_id  /code /  give_rec_id  / mid / top_mid  / put_type
     * */
    public function click_zs_cardslog($arr)
    {
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $arr['zs_card_id_all'];
        if ($zs_card_id) {
            $zs_card_id = json_decode($arr['zs_card_id_all'], true);

            $data = [];
            foreach ($zs_card_id as $k => $v) {
//                if (filterispay($v['zs_card_id']) == false && filteroffcard($v['zs_card_id']) == true) {
                $data[$k]['card_id'] = $arr['card_id'];
                $data[$k]['code'] = $arr['code'];
                $data[$k]['openid'] = $arr['openid'];
                $data[$k]['zs_card_id'] = $v['zs_card_id'];
                $data[$k]['give_rec_id'] = $arr['give_rec_id'];
                $data[$k]['mid'] = $arr['mid'];
                $data[$k]['top_mid'] = $arr['top_mid'];
                $data[$k]['put_sume'] = $v['zs_no'];
                $data[$k]['put_type'] = $arr['put_card'];
                $data[$k]['create_time'] = time();
//                }

            }

            $res = $CardGivecardLog->saveAll($data);
        } else {
            $res = '';
        }
        return $res;
    }

    //发送图文消息
    public function sendcardsnotice($param)
    {
        try {
            $CardFansNotice = new CardFansNotice();
            $info = $CardFansNotice->where(['gh_id' => $param['gh_id'], 'status' => 1])->find();
            if ($info) {
                $data = $param;
                $data['top_mid'] = $info['top_mid'];
                $data['notice_id'] = $info['id'];
                $notice = $this->getnotusercards($data);
                if ($notice['id'] !== 0) {
                    $mid = $this->getmid_topmid($info['top_mid']);
                    //发送图文消息
                    $Platurl = new Platurl();
                    $agent_url = $Platurl->getagenturl('top_mid', $info['top_mid']);
                    $arrs = [
                        [
                            'Title' => '您有可领取的优惠券！',
                            'Description' => $notice['cardlist'],
                            'PicUrl' => $info['img_url'],
                            'Url' => $agent_url . '/mobile.php?s=/cardusernu/getcardlist/mid/' . $mid . '/rec_id/' . $notice['id']
                        ]
                    ];
                } else {
                    $arrs = 0;
                }
            } else {
                $arrs = 0;
            }
            return $arrs;
        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            return $data2;
        }
    }

    //获取未领取卡券
    private function getnotusercards($param)
    {
        $CardGivecardLog = new CardGivecardLog();
        $cardlist = [];
        $cardlist = $CardGivecardLog->where(['openid' => $param['openid']])->select();
        if ($cardlist) {
            $CardGeneral = new CardGeneral();
            foreach ($cardlist as $k => $v) {
                if ($v['put_sume'] > $v['get_sume'] && getcardgetsume($v['zs_card_id']) > getcardgetuser($v['zs_card_id'], $v['openid']) && filteroffcard($v['zs_card_id'])) {
                    $givecardlist[] = $v['id'];
                    $cardlists[$k] = $CardGeneral->where(['card_id' => $v['zs_card_id']])->value('title');
                    $cardlists[$k] .= $v['put_sume'] - $v['get_sume'] . '[张]';
                }
            }
            if (isset($givecardlist) && isset($cardlists)) {
                $data['givecardlist'] = $givecardlist;
                $data['top_mid'] = $param['top_mid'];
                $data['openid'] = $param['openid'];
                $data['gh_id'] = $param['gh_id'];
                $data['notice_id'] = $param['notice_id'];
                $res['id'] = $this->rec_sendnotgetlog($data);
                $res['cardlist'] = implode(',', $cardlists);
            } else {
                $res['id'] = 0;
                $res['cardlist'] = '';

            }
        } else {
            $res['id'] = 0;
            $res['cardlist'] = '';
        }
        return $res;
    }

    /*新的发券过滤方法
         *
         * 2018/09/05
         *
         * */
    private function isgetputsume_rec($cardlist)
    {
        $re_arrs = "";
        try {
            $cardlists = array_column($cardlist, 'zs_card_id');
            foreach ($cardlist as $k => $v) {
                $arrs[$v['zs_card_id']]['card_id'] = $v['zs_card_id'];
                $arrs[$v['zs_card_id']]['zs_no'] = $v['zs_no'];
            }
            $map['card_id'] = array('in', implode(',', $cardlists));
            $CardGeneral = new CardGeneral();
            $card_list_info = $CardGeneral->where($map)->field('card_id,stocks,time_type,end_timestamp')->select();
            foreach ($card_list_info as $k => $v) {

                if (isset($arrs[$v['card_id']])) {
                    $card_list_info[$k]['zs_no'] = $arrs[$v['card_id']]['zs_no'];
                    if ($v['stocks'] >= $arrs[$v['card_id']]['zs_no']) {

                        if ($v['time_type'] == "DATE_TYPE_FIX_TIME_RANGE") {
                            if ($v['end_timestamp'] < time()) {
                                unset($card_list_info[$k]);
                            }
                        }
                    } else {
                        unset($card_list_info[$k]);
                    }
                }
            }
            $re_arrs = collection($card_list_info)->toArray();
            return $re_arrs;
        } catch (\Exception $e) {
            $re_arrs = "";
            return $re_arrs;
        }
    }

    //写入发送记录
    private function rec_sendnotgetlog($param)
    {
        $CardFansNoticeLog = new CardFansNoticeLog();
        $data['top_mid'] = $param['top_mid'];
        $data['notice_id'] = $param['notice_id'];
        $data['openid'] = $param['openid'];
        $data['gh_id'] = $param['gh_id'];
        $data['givecardlist'] = implode(',', $param['givecardlist']);
        $res = $CardFansNoticeLog->allowField(true)->save($data);
        if ($res) {
            $rec_id = $CardFansNoticeLog->id;
        } else {
            $rec_id = 0;
        }
        return $rec_id;
    }


    //获取appid  id
    public function getappid_ghid($gh_id)
    {
        $WxOpen = new WxOpen();
        $app = $WxOpen->where(['gh_id' => $gh_id])->field('authorizer_appid,id')->find();
        return $app;
    }

    //获取top_mid
    public function gettopmid_wxopenid($wx_open_id)
    {
        $Momerchant = new Momerchant();
        $top_mid = $Momerchant->where(['wx_open_id' => $wx_open_id])->value('id');
        return $top_mid;
    }

    //获取mid
    public function getmid_topmid($top_mid)
    {
        $Merchant = new Merchant();
        $id = $Merchant->where(['top_mid' => $top_mid])->value('id');
        return $id;
    }

}